﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace Master
{
    class SimpleTrafficLightStrategy : iTrafficLightStrategy
    {
        private Thread strategyThread;
        private Lane[] lanes;

        public void start(Dictionary<Side, List<Road>> roadDictionary)
        {
            List<Lane> totalList = new List<Lane>();
            foreach (List<Road> sublist in roadDictionary.Values)
                foreach (Road road in sublist)
                    foreach (Lane lane in road.getLanes())
                        totalList.Add(lane);
            lanes = totalList.ToArray();
            strategyThread = new Thread(handleTraffic);
            strategyThread.Start();
            
        }

        public void stop()
        {
            strategyThread.Abort();
        }

        private void handleTraffic()
        {
            try
            {
                while (true)
                {
                    foreach (Lane lane in lanes)
                    {
                        if (!lane.hasTrafficLight()) continue;
                        lane.trafficLight.Dispatcher.Invoke(
                            new Action(delegate(){lane.trafficLight.SetValue(TrafficLight.statusProperty, TrafficLightStatus.GREEN);})
                        );
                        Thread.Sleep(2000);
                        lane.trafficLight.Dispatcher.Invoke(
                            new Action(delegate() { lane.trafficLight.SetValue(TrafficLight.statusProperty, TrafficLightStatus.RED); })
                        );
                        Thread.Sleep(2000);
                    }
                }
            }
            catch (ThreadAbortException e)
            {
                Trace.WriteLine("Thread was aborted by: " + e.GetType());
                return;
            }
        }
    }
}
